<%--
  Created by IntelliJ IDEA.
  User: 跟我走吧灬
  Date: 2020/11/29
  Time: 20:30
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>出库单</title>
    <script src="${pageContext.request.contextPath}/style/jquery-2.1.0.js"></script>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/style/layui/css/layui.css">
    <script src="${pageContext.request.contextPath}/style/layui/layui.js"></script>
</head>
<style> #left {
    width: 40%;
    float: left;
}

#right {
    width: 60%;
    float: right;
}

</style>
<body>
<div id="left">
    <div class="layui-card">
        <div class="layui-card-header"></div>
        <div class="layui-card-body">
            <form class="layui-form" id="addFacForm" lay-filter="addFacForm">
                <input type="text" name="typename" style="display: none" id="typename">
                <input type="text" name="facname" style="display: none" id="facname">
                <input type="text" style="display: none" name="stock" id="stock">
                <div class="layui-form-item">
                    <label class="layui-form-label">类型</label>
                    <div class="layui-input-inline">
                        <select name="typeid" id="typeid" lay-verify="required" lay-filter="typeid">
                            <option value="">请选择类型</option>
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">设施产品名</label>
                    <div class="layui-input-inline">
                        <select name="facid" id="facid" lay-verify="required" lay-filter="facid" lay-search>
                            <option value="">请选择或者输入</option>
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">数量</label>
                    <div class="layui-input-inline">
                        <input type="text" name="count" id="count" required lay-verify="required|count|checkCount"
                               placeholder="请输入数量"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">售价</label>
                    <div class="layui-input-inline">
                        <input type="text" name="pmoney" id="pmoney" required lay-verify="required|pmoney" placeholder="请输入售价" class="layui-input">
                        <input type="text" style="display: none" name="outprice" id="outprice">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">供应商</label>
                    <div class="layui-input-inline">
                        <input type="text" name="gys" id="gys" required lay-verify="required|gys"
                               placeholder="请输入供应商"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button type="button" class="layui-btn" lay-submit lay-filter="formDemo">添加</button>
                        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
<div id="right">
    <%--数据表格--%>
    <table class="layui-hide" id="test" lay-filter="test"></table>
    <%--提交数据表格内容的表单--%>
    <form class="layui-form" id="ruku">
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">总数量:</label>
                <div class="layui-input-inline">
                    <input class="layui-input" id="totalcount" style="border: none" value="0" disabled>
                    <input name="totalcount" id="totalcount2" style="display: none">
                    <%--<input name="uid" style="display: none" value="${nowStaff.id}">--%>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">总金额(元):</label>
                <div class="layui-input-inline">
                    <input class="layui-input" id="totalprice" style="border: none" value="0" disabled>
                    <input name="totalprice" id="totalprice2" style="display: none">
                </div>
            </div>
        </div>
        <div class="layui-input-inline">
            <label class="layui-form-label">经手人:</label>
            <div class="layui-input-inline">
                <input type="text" name="jsr" id="jsr" lay-verify="required" class="layui-input">
                <input name="uid" style="display: none" value="${id}">
            </div>
            <button type="button" class="layui-btn" lay-submit lay-filter="ruku">提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </form>

</div>
<%--上侧删除按钮--%>
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm layui-btn-warm" lay-event="batchDel">批量删除</button>
    </div>
</script>

<%--右侧删除按钮--%>
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
</body>
<script>
    layui.use(['table', 'form', 'layer', 'jquery'], function () {
        var table = layui.table;
        var form = layui.form;
        var layer = layui.layer;
        var $ = layui.jquery;
        //设施的类型下拉框填充
        $.ajax({
            url: '${pageContext.request.contextPath}/ruku/querySsType',
            data: {},
            type: 'post',
            async: false,
            dataType: 'json',
            success: function (data) {
                var option = '';
                var dat = data;
                for (var i = 0; i < dat.length; i++) {
                    option += '<option value="' + dat[i]['id'] + '">' + dat[i]['name'] + '</option>';
                }

                $("#typeid").append(option);
                form.render('select');
            }
        });

        // 监听类型下拉框的选择，动态生成设施的下拉框
        form.on('select(typeid)', function (data) {
            if (data.value === "" || data.value === null) {
                $("#facid option").remove(); // 清空上次的option残留
                $("#facid").append("<option value=''>请选择或者输入</option>"); // 重新赋值初始选项
                form.render();
            } else {
                // 根据选中的value获得 值（text） 赋值到隐藏的input中
                let typename = data.elem[data.elem.selectedIndex].text;
                $("#typename").val(typename);
                $.ajax({
                    url: '${pageContext.request.contextPath}/ruku/querySs',
                    type: 'post',
                    async: false,
                    data: {id: data.value},
                    dataType: 'json',
                    success: function (result) {
                        $("#facid option").remove(); // 清空上次的option残留
                        $("#facid").append("<option value=''>请选择或者输入</option>"); // 重新赋值初始选项
                        var re = result;
                        var option = '';
                        if (re != null) {
                            for (let i = 0; i < re.length; i++) {
                                option += '<option value="' + re[i]['id'] + '">' + re[i]['name'] + '</option>';
                            }
                            $("#facid").append(option);
                        }
                        form.render('select');
                    }
                })
            }
        });

        // 监听设施的下拉框选择  给供应商input 赋值
        form.on('select(facid)', function (data) {

            var facname = data.elem[data.elem.selectedIndex].text;
            $("#facname").val(facname);
            $.ajax({
                url: '${pageContext.request.contextPath}/ruku/querySsid',
                type: 'post',
                dataType: 'JSON',
                data: {id: data.value},
                success: function (result) {

                    form.val('addFacForm',result)
                    $("#count").val("")
                    $("#stock").val(result.count)
                    $("#pmoney").val(result.pmoney)
                    $("#outprice").val(result.outprice)

                    /*var gys = result.data[0].gys;

                    // 供应商赋值
                    $("#gys").val(gys);
                    form.render('input')*/
                }

            })
        });

        // 渲染数据表格
        var tableData = [];
        table.render({
            elem: '#test'
            , data: tableData
            , toolbar: '#toolbarDemo'
            , totalRow: true
            , cols: [[
                {type: 'checkbox', fixed: 'left'}
                , {field: 'typename', title: '设施类型', sort: true}
                , {field: 'facname', title: '设施名称'}
                , {field: 'count', title: '数量', sort: true, edit: true}
                , {field: 'typeid', title: '类型id', hide: true}
                , {field: 'stock', title: '库存', hide: true}
                , {field: 'facid', title: '设施id', hide: true}
                , {field: 'pmoney', title: '售价(元)'}
                , {field: 'gys', title: '供应商'}
                , {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 100}
            ]]
        });

        //监听编辑单元格
        table.on('edit(test)', function (obj) {
            var data = obj.data;
            var oldText = $(this).prev().text();  // 单元格编辑之前的值
            var checkCount = /^[1-9]*[1-9][0-9]*$/;
            if (!checkCount.test(data.count)) {
                $(this).val(oldText)
                layer.msg("只能是正整数！！！")
            }else if (Number(data.stock) < Number(data.count)) { // 如果出库的量大于总库存
                $(this).val(oldText)
                layer.msg('现在的库存是' +data.stock+'出库数量不能大于这个数');}
            else{
                    var colIndex = $(obj.tr).attr("data-index");
                    tableData[colIndex].count = data.count;
                    changeTotalMoneyAndCount()
                }

        })

        /*监听头部工具栏*/
        table.on('toolbar(test)', function (obj) {
            if (obj.event === 'batchDel') {
                var checkStatus = table.checkStatus('test'),
                    //返回行的value
                    data = checkStatus.data;
                if (data.length > 0) {
                    layer.confirm('确定删除选中的行？', {icon: 3, title: '提示信息'}, function (index) {
                        //layui中找到CheckBox所在的行，并遍历找到行的顺序
                        $("div.layui-table-body table tbody input[name='layTableCheckbox']:checked").each(function () { // 遍历选中的checkbox
                            n = $(this).parents("tbody tr").index();  // 获取checkbox所在行的顺序
                            //从数组中移出选中的数据
                            tableData.splice(n, 1);
                            //移除行
                            $("div.layui-table-body table tbody ").find("tr:eq(" + n + ")").remove();
                            //如果是全选移除，就将全选CheckBox还原为未选中状态
                            $("div.layui-table-header table thead div.layui-unselect.layui-form-checkbox").removeClass("layui-form-checked");
                        });
                        changeTotalMoneyAndCount();
                        layer.close(index);
                    })
                } else {
                    layer.msg("请选择需要删除的行");
                }
            }
            if (obj.event === 'add') {
                layer.msg('add');
            }
        });

        //监听行工具事件
        table.on('tool(test)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data //获得当前行数据
            if (obj.event === 'del') {
                layer.confirm('真的要删除吗', function (index) {
                    obj.del(); //删除对应行（tr）的DOM结构
                    var colIndex = $(obj.tr).attr("data-index");
                    tableData.splice(colIndex, 1);
                    table.reload('test', {
                        data: tableData
                    });
                    changeTotalMoneyAndCount()

                    layer.close(index);
                });
            }

        });

        // 添加数据表格表单验证
        form.verify({
            count: [
                /^[0-9]*[1-9][0-9]*$/
                , '数量必须是正整数'
            ]
            , pmoney: [
                /^[1-9]\d*\.?\d*|0\.\d*$/
                , '价格只能是大于0的整数或者小数'
            ]
            ,checkCount:function (value, item) { //value：表单的值、item：表单的DOM对象
                var stock = $("#stock").val();
                if (Number(stock) < Number(value)) {
                    return '现在的库存是'+stock+'出库数量不能大于这个数';
                }
            }

        });

        // 添加数据表格表单提交
        form.on('submit(formDemo)', function (data) {
            var flag = false;
            for (var i = 0; i < tableData.length; i++) {
                if (data.field.facid === tableData[i].facid) {
                    flag = true;
                    break;
                }
            }
            // 如果存在相同的数据，不能添加
            if (flag) {
                layer.msg("已经存在相同的数据，只需要修改表格中的数量即可！！！")
            } else {
                layer.msg("添加成功！！！")
                // 将表单的数据添加到tableData中
                tableData.push(data.field);
                // 重新刷新表格
                table.reload('test', {
                    data: tableData
                });
                changeTotalMoneyAndCount()
                $("#facid").empty() // 清空上次的option残留
                $("#facid").append("<option value=''>请选择或者输入</option>") // 重新赋值初始选项
                $("#addFacForm")[0].reset();//刷新表格
            }
            return false;
        });
        // 入库表单 表单提交
        form.on('submit(ruku)', function (data) {


            if (tableData.length === 0) {
                layer.msg("请先添加数据到表格中，再进行入库操作！！！")
            } else {
                $.ajax({
                    url: '${pageContext.request.contextPath}/chuku/addchuku',
                    type: 'post',
                    async: false,
                    data: {data: JSON.stringify(data.field), tableData: JSON.stringify(tableData)},
                    success: function (a) {

                        if (a > 0) {
                            layer.msg("出库成功！！！")
                            $("#ruku")[0].reset();
                            tableData = []
                            table.reload('test', {
                                data: tableData
                            });
                        } else {
                            layer.msg("出库失败！！！")
                        }
                    },
                    dataType: 'json'
                })
            }
            return false;
        })

        // 计算总价和总数量
        function changeTotalMoneyAndCount() {
            var totalprice = 0;
            var totalcount = 0;
            for (var i = 0; i < tableData.length; i++) {
                totalprice += Number(tableData[i].pmoney) * Number(tableData[i].count);
                totalcount += Number(tableData[i].count);
            }
            $("#totalprice").val(totalprice);
            $("#totalprice2").val(totalprice);
            $("#totalcount").val(totalcount);
            $("#totalcount2").val(totalcount);
        }

    });

</script>
</html>